package gnssio

import (
	"dgo/goutils/utils"
	"sync/atomic"
	"time"
)

type Transmitter struct {
	input  I_Comm
	output I_Comm
	// 注意8字节对齐
	InputSize  uint64
	OutputSize uint64

	LastInputTime  time.Time
	LastOutputTime time.Time

	LastOutputRet int
}

func NewTransmitter() *Transmitter {
	rval := &Transmitter{
		LastOutputRet: 0,
	}
	return rval
}

/*
*

	on input
*/
func (this *Transmitter) OnReceive(sender I_Comm, buf []byte, len int) {
	if sender == this.input {
		atomic.AddUint64(&this.InputSize, uint64(len))
		this.LastInputTime = time.Now()
		if this.output != nil {
			n := this.output.Send(buf, len)
			this.LastOutputRet = n
			if n > 0 {
				//fmt.Printf("Outputsize:%d, %X, n:%d\n", this.CorsDataSize, &this.CorsDataSize, n)
				atomic.AddUint64(&this.OutputSize, uint64(n))
				this.LastOutputTime = time.Now()
			}
		}
	} else if sender == this.output {
		n := this.input.Send(buf, len)
		utils.Log.Debugf("output(len:%d):%s, hex:%s, 发送长度:%d", len, string(buf[:len]), utils.BufToHexStr(buf, len, " "), n)
	}
}

func (this *Transmitter) OnConnect(sender I_Comm) {

}

func (this *Transmitter) OnDisconnect(sender I_Comm) {

}

func (this *Transmitter) SetInput(val I_Comm) {
	if this.input != val {
		if this.input != nil {
			this.input.RemoveListener(this)
		}
		this.input = val
		this.input.AddListener(this)
	}
}

func (this *Transmitter) SetOutput(val I_Comm) {
	if this.output != val {
		if this.output != nil {
			this.output.RemoveListener(this)
		}
		this.output = val
		this.output.AddListener(this)
	}

}
